﻿namespace Atomic.Data.AdoNet
{
    using System;
    using System.Data;
    using System.Data.Common;
    using System.Threading.Tasks;

    /// <summary>
    /// 数据提供程序基类。
    /// </summary>
    public abstract partial class DataProviderBase : IDataProvider
    {
        /// <summary>
        /// 数据库连接字符串。
        /// </summary>
        private string _connectionString = string.Empty;

        /// <summary>
        /// 初始化数据提供程序基类。
        /// </summary>
        public DataProviderBase()
        {
        }

        /// <summary>
        /// 初始化数据提供程序基类。
        /// </summary>
        /// <param name="connectionString">数据库连接字符串。</param>
        public DataProviderBase(string connectionString)
        {
            this._connectionString = connectionString;
        }

        /// <summary>
        /// 数据库连接字符串。
        /// </summary>
        protected string ConnectionString
        {
            get
            {
                if (string.IsNullOrWhiteSpace(this._connectionString))
                {
                    this._connectionString = AtomicConfigurationManager.Current.GetDefaultConnection().ConnectionString;
                }

                return this._connectionString;
            }
            set
            {
                this._connectionString = value;
            }
        }

        /// <summary>
        /// 枚举,标识数据库连接是由BaseDbHelper提供还是由调用者提供。
        /// </summary>
        protected enum DbConnectionOwnership
        {
            /// <summary>
            /// 由BaseDbHelper提供连接。
            /// </summary>
            Internal,

            /// <summary>
            /// 由调用者提供连接。
            /// </summary>
            External
        }

        /// <summary>
        /// 查询数据。
        /// </summary>
        /// <param name="commandType">命令类型。</param>
        /// <param name="sql">SQL 语句或者存储过程名称。</param>
        /// <param name="commandParameters">SQL 参数。</param>
        /// <returns>数据读取器。</returns>
        public IDataReader SqlQuery(CommandType commandType, string sql, params IDataParameter[] commandParameters)
        {
            return this.ExecuteReader(ConnectionString, commandType, sql, commandParameters);
        }

        /// <summary>
        /// 查询单条数据。
        /// </summary>
        /// <param name="commandType">命令类型。</param>
        /// <param name="sql">SQL 语句或者存储过程名称。</param>
        /// <param name="commandParameters">SQL 参数。</param>
        /// <returns>查询结果。</returns>
        public object Single(CommandType commandType, string sql, params IDataParameter[] commandParameters)
        {
            if (ConnectionString == null || ConnectionString.Length == 0)
            {
                throw new ArgumentNullException("ConnectionString");
            }

            // 创建并打开数据库连接对象,操作完成释放对象.
            using (DbConnection connection = this.GetDbProviderFactory().CreateConnection())
            {
                connection.ConnectionString = ConnectionString;
                connection.Open();

                // 调用指定数据库连接字符串重载方法.
                return ExecuteScalar(connection, null, commandType, sql, commandParameters);
            }
        }

        /// <summary>
        /// 执行 SQL 命令。
        /// </summary>
        /// <param name="commandType">命令类型。</param>
        /// <param name="sql">SQL 语句或者存储过程名称。</param>
        /// <param name="commandParameters">SQL 参数。</param>
        /// <returns>影响行数。</returns>
        public int ExecuteSqlCommand(CommandType commandType, string sql, params IDataParameter[] commandParameters)
        {
            if (ConnectionString == null || ConnectionString.Length == 0)
                throw new ArgumentNullException("ConnectionString");

            using (DbConnection connection = this.GetDbProviderFactory().CreateConnection())
            {
                connection.ConnectionString = ConnectionString;
                connection.Open();

                return ExecuteNonQuery(connection, null, commandType, sql, commandParameters);
            }
        }

        #region protected method

        #region ExecuteNonQuery

        /// <summary>
        /// 执行指定数据库连接对象的命令
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new IDataParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">一个有效的数据库连接对象</param>
        /// <param name="transaction">一个有效的事务,或者为 'null'</param>
        /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
        /// <param name="commandText">T存储过程名称或SQL语句</param>
        /// <param name="commandParameters">SqlParamter参数数组</param>
        /// <returns>返回影响的行数</returns>
        protected virtual int ExecuteNonQuery(
            DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, params IDataParameter[] commandParameters)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            // 创建DbCommand命令,并进行预处理
            DbCommand cmd = this.GetDbProviderFactory().CreateCommand();
            cmd.CommandTimeout = 600;
            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

            // Finally, execute the command
            int retval = cmd.ExecuteNonQuery();

            // 清除参数,以便再次使用.
            cmd.Parameters.Clear();

            if (mustCloseConnection)
            {
                cmd.Dispose();
                connection.Close();
            }
            return retval;
        }

        #endregion

        #region ExecuteScalar

        /// <summary>
        /// 执行指定数据库连接对象的命令,指定参数,返回结果集中的第一行第一列.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new IDataParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">一个有效的数据库连接对象</param>
        /// <param name="transaction">一个有效的事务,或者为 'null'</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
        /// <returns>返回结果集中的第一行第一列</returns>
        protected virtual object ExecuteScalar(DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, params IDataParameter[] commandParameters)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            object retval = null;

            try
            {
                // 创建DbCommand命令,并进行预处理
                DbCommand cmd = this.GetDbProviderFactory().CreateCommand();

                bool mustCloseConnection = false;
                PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

                // 执行DbCommand命令,并返回结果.
                retval = cmd.ExecuteScalar();

                // 清除参数,以便再次使用.
                cmd.Parameters.Clear();

                if (mustCloseConnection)
                    connection.Close();
            }
            catch
            {
                if (connection != null)
                {
                    connection.Close();
                }
                throw;
            }

            return retval;
        }

        #endregion

        #region ExecuteReader

        /// <summary>
        /// 执行指定数据库连接对象的数据阅读器.
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名或 SQL 语句</param>
        /// <param name="commandParameters">IDataParameters 参数数组, 如果没有参数则为 'null'</param>
        /// <returns>返回包含结果集的 IDataReader</returns>
        protected virtual IDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params IDataParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("ConnectionString");

            DbConnection connection = null;

            try
            {
                connection = this.GetDbProviderFactory().CreateConnection();
                connection.ConnectionString = connectionString;
                connection.Open();

                return ExecuteReader(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
            }
            catch
            {
                // If we fail to return the SqlDatReader, we need to close the connection ourselves
                if (connection != null)
                {
                    connection.Close();
                }
                throw;
            }
        }

        /// <summary>
        /// 执行指定数据库连接对象的数据阅读器.
        /// </summary>
        /// <remarks>
        /// 如果是BaseDbHelper打开连接,当连接关闭DataReader也将关闭.
        /// 如果是调用都打开连接,DataReader由调用都管理.
        /// </remarks>
        /// <param name="connection">一个有效的数据库连接对象</param>
        /// <param name="transaction">一个有效的事务,或者为 'null'</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名或 SQL 语句</param>
        /// <param name="commandParameters">IDataParameters参数数组,如果没有参数则为'null'</param>
        /// <param name="connectionOwnership">标识数据库连接对象是由调用者提供还是由BaseDbHelper提供</param>
        /// <returns>返回包含结果集的DbDataReader</returns>
        protected DbDataReader ExecuteReader(DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, IDataParameter[] commandParameters, DbConnectionOwnership connectionOwnership)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            bool mustCloseConnection = false;
            // 创建命令
            DbCommand cmd = this.GetDbProviderFactory().CreateCommand();
            cmd.CommandTimeout = 180;
            try
            {
                PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

                // 创建数据阅读器
                DbDataReader dataReader;

                if (connectionOwnership == DbConnectionOwnership.External)
                {
                    dataReader = cmd.ExecuteReader();
                }
                else
                {
                    dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }

                bool canClear = true;
                foreach (IDataParameter commandParameter in cmd.Parameters)
                {
                    if (commandParameter.Direction != ParameterDirection.Input)
                        canClear = false;
                }

                if (canClear)
                {
                    //cmd.Dispose();
                    cmd.Parameters.Clear();
                }

                return dataReader;
            }
            catch
            {
                if (mustCloseConnection)
                    connection.Close();
                throw;
            }
        }

        #endregion

        #region PrepareCommand

        /// <summary>
        /// 预处理用户提供的命令,数据库连接/事务/命令类型/参数
        /// </summary>
        /// <param name="command">要处理的DbCommand</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="transaction">一个有效的事务或者是null值</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
        /// <param name="commandText">存储过程名或都SQL命令文本</param>
        /// <param name="commandParameters">和命令相关联的IDataParameter参数数组,如果没有参数为'null'</param>
        /// <param name="mustCloseConnection"><c>true</c> 如果连接是打开的,则为true,其它情况下为false.</param>
        protected virtual void PrepareCommand(DbCommand command, DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, IDataParameter[] commandParameters, out bool mustCloseConnection)
        {
            if (command == null)
                throw new ArgumentNullException("command");
            if (commandText == null || commandText.Length == 0)
                throw new ArgumentNullException("commandText");

            // If the provided connection is not open, we will open it
            if (connection.State != ConnectionState.Open)
            {
                mustCloseConnection = true;
                connection.Open();
            }
            else
            {
                mustCloseConnection = false;
            }

            // 给命令分配一个数据库连接.
            command.Connection = connection;

            // 设置命令文本(存储过程名或SQL语句)
            command.CommandText = commandText;

            // 分配事务
            if (transaction != null)
            {
                if (transaction.Connection == null)
                    throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
                command.Transaction = transaction;
            }

            // 设置命令类型.
            command.CommandType = commandType;

            // 分配命令参数
            if (commandParameters != null)
            {
                AttachParameters(command, commandParameters);
            }
            return;
        }

        /// <summary>
        /// 将IDataParameter参数数组(参数值)分配给DbCommand命令.
        /// 这个方法将给任何一个参数分配DBNull.Value;
        /// 该操作将阻止默认值的使用.
        /// </summary>
        /// <param name="command">命令名</param>
        /// <param name="commandParameters">IDataParameters数组</param>
        private void AttachParameters(DbCommand command, IDataParameter[] commandParameters)
        {
            if (command == null)
                throw new ArgumentNullException("command");
            if (commandParameters != null)
            {
                foreach (IDataParameter p in commandParameters)
                {
                    if (p != null)
                    {
                        // 检查未分配值的输出参数,将其分配以DBNull.Value.
                        if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) &&
                            (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }
                        command.Parameters.Add(p);
                    }
                }
            }
        }

        #endregion

        #endregion

        /// <summary>
        /// 获取数据库连接对象工厂。
        /// </summary>
        /// <returns>数据库连接对象工厂。</returns>
        protected abstract DbProviderFactory GetDbProviderFactory();
    }
}